<template>
  <div v-if="COMPLEXSTATE">
    <div v-if="!this.complexPassState" class="image-gallery">
      <el-header>
        <el-steps :active="active" align-center style="width: 80vw">
          <el-step v-for="(step, index) in steps" :key="index" :title="step.title" :description="step.description"></el-step></el-steps>
      </el-header>
      <div class="pagination-block" style="width: 70vw">
        <el-form v-for="(form, formIndex) in forms" :key="formIndex" :inline="true" class="demo-dynamic">
          <div v-for="(item, itemIndex) in form.message" v-if="canSee[formIndex + 1]" :key="itemIndex" class="dynamic-box">
            <el-form-item>{{ item.title }}</el-form-item>
            <el-form-item label="项目名称" prop="name">
              <el-input :disabled="form.message[0].complexTypeNo ==='20240327141811'||form.message[0].complexTypeNo ==='20240327141812'" v-model="item.name"></el-input>
            </el-form-item>
            <el-form-item label="分数（填写正分）" prop="score">
              <el-input-number :min="0" :value-on-clear="0" :disabled="form.message[0].complexTypeNo ==='20240327141811'||form.message[0].complexTypeNo ==='20240327141812'" v-model="item.score"></el-input-number>
            </el-form-item>
            <el-form-item label="证明材料" prop="photoUrl" style=" align-items: center;">
              <el-upload accept=".jpeg,.png,.jpg" :before-upload="checkFileType" class="avatar-uploader" style="  border: 1px dashed #d9d9d9;
                    border-radius: 6px;
                    cursor: pointer;
                    position: relative;
                    overflow: hidden;" :action="'/api/complex_related/uploadPhoto'" :headers="this.headerObject" :show-file-list="false" :data="item" :on-success="res=>handleSuccess(res,item)">
                <div style="width: 80px;">
                  <img width="80" v-if="item.photoUrl!==''" :src="item.photoUrl" :alt="item.photoUrl">
                  <img width="80" v-else src="" alt="">
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button v-if="form.message.length > 1" @click="removeDomain(form.message, itemIndex)">删除</el-button>
            </el-form-item>
          </div>
          <div v-if="canSee[formIndex + 1]" style="display: flex; justify-content: center;">
            <el-form-item style="display: flex; text-align: center;">
              <el-button v-if="form.message[0].complexTypeNo !=='20240327141811'&&form.message[0].complexTypeNo !=='20240327141812'" @click="addDomain(formIndex,form.message[0].title,form.message[0].complexTypeNo)" type="primary">新增奖项</el-button>
            </el-form-item>
            <el-form-item style="display: block; text-align: center">
              <el-button @click="seeAll()" type="primary">暂存数据</el-button>
              <el-button v-if="formIndex!==15" @click="nextItem(formIndex+1)" type="primary">下一步（没有就点下一步）
              </el-button>
              <el-button v-else @click="seeAll()" type="primary">整体查看</el-button>
            </el-form-item>
            <el-form-item style="display: block; text-align: center;">
              <el-button v-if="formIndex!==0" @click="back(formIndex+1)" type="primary">上一步</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div v-html="detailedRule"></div>
    </div>
    <h1 style="text-align: center" v-else>本年度已被审批</h1>
  </div>
  <div style="text-align: center;font-size: 50px" v-else>
    综测未开放
  </div>
  <el-dialog v-model="this.$store.state.complexUpload" :close-on-click-modal="false" title="综测详情信息" width="850px">
    <Complex v-if="this.$store.state.complexUpload"/>
  </el-dialog>
</template>

<script>
import Complex from "@/template/Complex.vue";
import Information from "@/template/Information.vue";
import request from "@/util/request.js";
import {photoIp, year,COMPLEXSTATE} from "../../../public/static/config.js";
import aes from "@/util/aes.js";
import router from "@/router/index.js";
export default {
  components: {Information, Complex},
  data() {
    return {
      COMPLEXSTATE:COMPLEXSTATE,
      complexPassState: false, // 已审批
      allDetailedRules: [], // 所有评分细则
      detailedRule: "", // 评分细则
      year: year,
      accountNo: JSON.parse(localStorage.getItem('user')).accountNo,
      active: 0,
      num: 1,
      canSee: {
        1: true,
        2: false,
      },
      steps: [
        {title: "思想品德", description: ""},
        {title: "学业成绩", description: ""},
        {title: "身心素质", description: ""},
        {title: "社会工作与对外交流", description: ""},
        {title: "公益服务与社会实践", description: ""},
        {title: "文体艺活动", description: ""},
        {title: "学业与创新创业", description: ""},
      ],
      forms: [
        {message: [{title: '政治素养加分项', complexTypeNo: "20240327141803", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '政治素养减分项', complexTypeNo: "20240327141805", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '行为规范加分项', complexTypeNo: "20240327141807", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '行为规范减分项', complexTypeNo: "20240327141809", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '学业成绩', complexTypeNo: "20240327141811", name: '', score: 0, photoUrl: ''}],},
        {message: [{title: '身心素质加分项', complexTypeNo: "20240327141812", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '身心素质减分项', complexTypeNo: "20240327141813", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '社会工作加分项', complexTypeNo: "20240327141815", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '对外交流加分项', complexTypeNo: "20240327141817", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '公益服务加分项', complexTypeNo: "20240327141819", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '社会实践加分项', complexTypeNo: "20240327141820", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '文体艺活动加分项', complexTypeNo: "20240327141821", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '学科竞赛加分项', complexTypeNo: "20240327141822", name: '', score: 0, photoUrl: ''}]},
        {
          message: [{
            title: '专业技能及职业资格证书加分项',
            complexTypeNo: "20240327141824",
            name: '',
            score: 0,
            photoUrl: ''
          }]
        },
        {message: [{title: '创新创业大赛加分项', complexTypeNo: "20240327141825", name: '', score: 0, photoUrl: ''}]},
        {message: [{title: '学术与科研加分项', complexTypeNo: "20240327141828", name: '', score: 0, photoUrl: ''}]}
      ],
      all: [],
      allSee: false,
      headerObject: {
        "account": JSON.parse(localStorage.getItem('user')).accountNo,
        "token": JSON.parse(localStorage.getItem('user')).token
      },
    };
  },
  created() {
    if (COMPLEXSTATE){
      this.getAllDetailedRules()
      if (router.currentRoute.value.query.accountNo !== undefined) {
        this.accountNo = router.currentRoute.value.query.accountNo
        this.year = router.currentRoute.value.query.year
      }
      this.getOne()
    }
  },
  methods: {
    // 获取综测细则
    getAllDetailedRules() {
      request.get("/complex_rule/all").then(res => {
        this.allDetailedRules.push(...res.data.data)
        this.nextItem(0)
      })
    },
    photoIp() {
      return photoIp
    },
    // 材料上传成功回调
    handleSuccess(res, item) {
      res = aes.decrypt(res)
      item.photoUrl = res.data
      this.$message({
        type: 'success',
        message: '上传成功!'
      });
    },
    // 检查文件类型
    checkFileType(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      // jpeg,.png,.jpg,.bmp,.gif
      if (
          fileType === '.jpg' ||
          fileType === '.png' ||
          fileType === '.jpeg'
      ) {// 验证通过
      } else {
        this.$message.error(
            '不是,jpeg,.png,.jpg文件,请上传正确的图片类型'
        )
        return false
      }
    },
    /**
     * 获取学业成绩
     */
    getGrade() {
      request.get("/year_grade/getByAccountNoAndYear?accountNo=" + this.accountNo + "&year=" + this.year).then(res => {
        let data = res.data.data
        if (data === undefined) {
          this.forms[4].message.at(0).name = "无学业成绩数据，请联系辅导员"
        } else {
          this.forms[4].message.at(0).name = "平均学分绩点 " + data.avgCreditPoint + " 分"
          this.forms[4].message.at(0).score = ((parseFloat(data.avgCreditPoint) + 5) * 10).toFixed(1)
        }
      })
    },
    /**
     * 获取体测信息
     */
    getSport() {
      request.get("/related_sport/getByAccountNoAndYear?accountNo=" + this.accountNo + "&year=" + this.year).then(res => {
        let data = res.data.data
        if (data === undefined) {
          this.forms[5].message.at(0).name = "无国测成绩数据，请联系辅导员"
        } else {
          this.forms[5].message.at(0).name = "国测成绩: " + data.score
          this.forms[5].message.at(0).score = this.calculateA3Score(data.score)
        }
      })
    },
    calculateA3Score(nationalTestScore) {
      if (nationalTestScore > 80) {
        return 20; // 国测良好，分数为20分
      } else if (nationalTestScore < 60) {
        return 10; // 国测不及格，分数为10分
      }else if (nationalTestScore === "违纪") {
        return 0; // 国测违纪，分数为0分
      } else {
        return 15; // 其他情况为国测及格，分数为15分
      }
    },
    calculateA3Grade(nationalTestScore, nationalTest) {
      if (nationalTest === "免测") {
        return "国测免测"; // 如果国测为“免测”，返回“国测免测”
      } else if (nationalTestScore > 80) {
        return "国测良好"; // 国测良好
      } else if (nationalTest === "违纪") {
        return "违纪"; // 违纪
      }else if (nationalTestScore < 60) {
        return "国测不及格"; // 国测不及格
      } else {
        return "国测及格"; // 国测及格
      }
    },
    // 获取信息(未提交过的话获取国测和学业成绩)
    getOne() {
        request.get(`/complex_related/getOne?accountNo=${this.accountNo}` + "&year=" + this.year).then(res => {
          let data = []
          if (res.data.data === undefined) {
            this.forms[0].message.at(0).name = "班主任评分"
            this.forms[0].message.at(0).score = 15
            this.getGrade()
            this.getSport()
          } else {
            if (res.data.data.state === "1") {
              // 通过
              this.complexPassState = true
              return
            } else if (res.data.data.state === "3") {
              // 驳回
              this.$notify({
                title: "已被驳回，请查看以下驳回原因",
                message: res.data.data.rejection,
                duration: 0
              });
            }
            data = res.data.data.contentList;
            // 遍历后端获取到的列表
            data.forEach(item => {
              // 找到对应的表单
              const formIndex = this.forms.findIndex(form => form.message[0].complexTypeNo === item.complexTypeNo);
              if (formIndex !== -1) {
                // 更新表单的分数
                if (this.forms[formIndex].message[0].score === 0) {
                  this.forms[formIndex].message = []
                }
                this.forms[formIndex].message.push(item);
              }
            });
          }
        });
    },
    // 下一个项目
    nextItem(formIndex) {
      switch (formIndex) {
        case 0:
          this.detailedRule = this.allDetailedRules[0].content + this.allDetailedRules[1].content;
          break;
        case 4:
          // 如果未获取到学业成绩数据重新获取
          if (this.forms[4].message.at(0).score === 0) {
            this.getGrade()
          }
          this.active = 1;
          this.detailedRule = this.allDetailedRules[2].content;
          break;
        case 5: {// 如果未获取到国测成绩数据重新获取
          if (this.forms[5].message.at(0).score === 0)
            this.getSport()
        }
          this.active = 2;
          this.detailedRule = this.allDetailedRules[3].content;
          break;
        case 7:
          this.active = 3;
          this.detailedRule = this.allDetailedRules[4].content;
          break;
        case 9:
          this.active = 4;
          this.detailedRule = this.allDetailedRules[5].content;
          break;
        case 11:
          this.active = 5;
          this.detailedRule = this.allDetailedRules[6].content;
          break;
        case 12:
          this.active = 6;
          this.detailedRule = this.allDetailedRules[7].content + this.allDetailedRules[8].content;
          break;
        case 13:
          this.active = 7;
          break;
      }
      this.canSee[formIndex] = false;
      this.canSee[formIndex + 1] = true;
    },
    // 删除项目
    removeDomain(message, itemIndex) {
      message.splice(itemIndex, 1);
    },
    // 新增一项目
    addDomain(formIndex, title, complexTypeNo) {
      this.forms[formIndex].message.push({
        title: title,
        complexTypeNo: complexTypeNo,
        name: "",
        score: "",
      });
    },
    // 返回上一个项目
    back(formIndex) {
      switch (formIndex) {
        case 5:
          this.active = 0;
          this.detailedRule = this.allDetailedRules[0].content + this.allDetailedRules[1].content;
          break;
        case 6:
          this.active = 1;
          this.detailedRule = this.allDetailedRules[2].content;
          break;
        case 8:
          this.active = 2;
          this.detailedRule = this.allDetailedRules[3].content;
          break;
        case 10:
          this.active = 3;
          this.detailedRule = this.allDetailedRules[4].content;
          break;
        case 12:
          this.active = 4;
          this.detailedRule = this.allDetailedRules[5].content;
          break;
        case 13:
          this.active = 5;
          this.detailedRule = this.allDetailedRules[6].content;
          break;
        case 14:
          this.active = 6;
          this.detailedRule = this.allDetailedRules[7].content + this.allDetailedRules[8].content;
          break;
      }
      this.canSee[formIndex] = false;
      this.canSee[formIndex - 1] = true;
    },
    // 整体查看
    seeAll() {
      let result = []
      this.forms.forEach((item, index) => {
        result.push(...item.message)
      })
      this.$store.commit('complexUploadSetTrue', result)
      this.$store.commit('setAccountN0', this.accountNo)
      this.$store.commit("setYear", this.year)
    }
  },
};
</script>
<style scoped>

.image-gallery {
  justify-content: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pagination-block {
  display: flex;
  justify-content: center;
  background-color: white;
  padding: 10px;
}

@media screen and (max-width: 768px) {
  .pagination-block {
    display: flex;
    justify-content: center;
    background-color: white;
    margin-top: 80px;
  }
}


/* 头像上传*/
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
  width: 140px;
  justify-content: center;
}

</style>
